#!/usr/bin/env python
#coding: utf-8
'''
Created on 2017年4月17日

@author: Administrator
'''

from celery.task import task
from common.decorators.celery import task_exception_handler
from django.core.mail import EmailMessage as DjangoEmailMessage, get_connection
from message import settings
from message.models import MobileMessage, EmailMessage
import datetime
import logging
import random
import urllib2
import urllib




task_log = logging.getLogger('django.task')

@task
@task_exception_handler
def send_sms(mobile, content, recv_user=None):
    '''
    function: 发短信 
    mobile: 手机号
    content: 短信内容， 默认情况下短信内容会在头部自动加上【爱福窝】字样，所以content中不需要再加这个头
    ps: 当短信内容>70汉字的时候会算作2条以上的短信，所以没有特殊情况的话先预检内容长度。
    return：rsp 提交结果
        rsp[0] 状态值：
        -1    账号不存在
        -2    密码错误
        -3    账号被锁
        -4    账号余额为0
        -5    短信内容含有关键字
        -6    标示号taskId有误
        -7    短信内容前没加后缀（见注释2）
        -8    提交的短信号码低于账号最低配置
        -9    短信发送量超出当日规定数量
        0    短信发送成功
        1    其他错误
        2    账号信息有误
        3    短信内容或号码为空
        4    账号余额不够发送当前短信
        5    发送短信过程中出错
        ###### 自定义错误
        6    手机号码错误
        20    接口调用失败，连接被重置
    '''
    
    # 加上爱福窝头部
    if type(content) is unicode:
        content = content.encode('utf-8')
    full_content = '%s%s' % (u"".encode('utf-8'), content.replace('&', '＆'))
    
    # 创建一条未发送的数据库记录
    mobile_message = MobileMessage(mobile=mobile,
                                   content=full_content,
                                   recv_user=recv_user,
                                   is_pushed=False)
    mobile_message.save()
    
    # 向短信服务商接口提交发送
    task_id = '_'.join([settings.MESSAGE_SMS_ACCOUNT,
                        datetime.datetime.strftime(datetime.datetime.now(), "%Y%m%d%H%M%S"),
                        'http',
                        ''.join(random.sample('0123456789', 6))])
    params = {
        "account": settings.MESSAGE_SMS_ACCOUNT,
        "password": settings.MESSAGE_SMS_PASSWORD,
        "content":'%s' % full_content,
        "phonelist": mobile,
        "taskId": task_id,
        "sendtime": '',
    }
    params = urllib.urlencode(params)
    rsp = urllib2.urlopen('%s?%s' % (settings.MESSAGE_SMS_SEND_API, params))
    rsp_data = rsp.read()
    rsp.close()

    # 解析返回结果
    code = rsp_data.split(',')[0]
    
    if code == '0':
        MobileMessage.objects.filter(id=mobile_message.id).update(is_pushed=True, modify_time=datetime.datetime.now())
        task_log.info(u'Send mobile message id=%s success.' % mobile_message.id)
    else:
        task_log.error(u'Send mobile message id=%s failed with error %s.' % (mobile_message.id, rsp_data))


@task
@task_exception_handler
def send_email_message(message_id):
    '''
    function: 异步发送email消息
     
    message_id - email消息id
    '''
    
    try:
        message = EmailMessage.objects.get(id=message_id, is_pushed=False)
    except EmailMessage.DoesNotExist:
        return
    
    connection = get_connection(backend='common.core.mail.backends.PublicEmailBackend')
    email = DjangoEmailMessage(subject=message.subject,
                               body=message.content,
                               from_email=settings.PUBLIC_EMAIL_HOST_USER,
                               to=[message.email, ],
                               connection=connection,
                               headers={'From': '<%s>' % settings.PUBLIC_EMAIL_HOST_USER})
    email.content_subtype = 'html'
    
    sended_count = email.send()
    if sended_count > 0:
        EmailMessage.objects.filter(id=message.id).update(is_pushed=True, modify_time=datetime.datetime.now())
        return True
    else:
        return False
